const {
  appid,
  secret
} = require('../config/wx.config')

const https = require('https')

const enCode =async  (ucode) => {
  let promiseUid = new Promise((resolve,reject)=>{
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${ucode}&grant_type=authorization_code`
    //转发请求
    let data = ''
    https.get(url, (res) => {
      if (res.statusCode == 200) {
        res.on('data', (chunk) => { //接收流数据
          data += chunk;
        });
        res.on('end', () => {
          let payload = JSON.parse(data)
          resolve(payload.openid)
        })
      } else {
        console.error(res.statusCode, '失败');
        reject
      }
    })
  })
  let uid = await promiseUid
  return uid
}


module.exports = {
  enCode
}